package com.hqq.concurrency.reactor.framework;

import com.hqq.concurrency.reactor.LoggingHandler;
import sun.rmi.transport.Channel;

import java.io.IOException;
import java.util.List;

/**
 * App
 * Created by heqianqian on 2017/8/6.
 */
public class App {

    private NIOReactor reactor;
    private List<AbstractNIOChannel> channelList;
    private Dispatcher dispatcher;

    public App(Dispatcher dispatcher) {
        this.dispatcher = dispatcher;
    }

    public static void main(String[] args) {
        new App(new ThreadPoolDispatcher(5));
    }

    public void start() throws IOException {
        reactor = new NIOReactor(dispatcher);

        LoggingHandler loggingHandler = new LoggingHandler();

        reactor.registerChannel(tcpChannel(6666, loggingHandler))
                .registerChannel(tcpChannel(6667, loggingHandler))
                .registerChannel(udpChannel(6668, loggingHandler)).start();
    }

    public void stop() throws IOException, InterruptedException {
        reactor.stop();
        dispatcher.stop();
        for (AbstractNIOChannel channel : channelList) {
            channel.getJavaChannel().close();
        }
    }

    private AbstractNIOChannel tcpChannel(int port, ChannelHandler handler) throws IOException {
        NIOServerSocketChannel serverSocketChannel = new NIOServerSocketChannel(port, handler);
        serverSocketChannel.bind();
        channelList.add(serverSocketChannel);
        return serverSocketChannel;
    }

    private AbstractNIOChannel udpChannel(int port, ChannelHandler handler) throws IOException {
        NIODatagramChannel datagramChannel = new NIODatagramChannel(port, handler);
        datagramChannel.bind();
        channelList.add(datagramChannel);
        return datagramChannel;
    }

}
